import Vue from 'vue'
import Component from './func-notification'

// 创建组件
const NotificationConstructor = Vue.extend(Component)
// console.log(NotificationConstructor)

const instances = []
let seed = 1

// 从数组中删除instance
const removeInstance = instance => {
    if (!instance) return
    const len = instances.length
    const index = instances.findIndex(item => item.id === instance.id)

    instances.splice(index,1)

    // 刚移除的元素的高度
    const removeHeight = instance.vm.height

    if (len <= 1) return
    for (let i = index ;i<len -1 ;i++){
        instances[i].verticalOffset = (instances[i].verticalOffset - removeHeight) - 16
    }
}

const notify = (options) => {
    // 服务端渲染不需要展示dom
    if (Vue.prototype.$isServer) return

    const {autoClose,...rest} = options

    const instance = new NotificationConstructor({
        // propsData:options
        propsData:{
            ...rest
        },
        data:{
            autoClose: autoClose === undefined ? 3000 : autoClose
        }
    })

    // console.log(options)
    // console.log(instance)

    const id = `notification_${seed++}`
    instance.id = id

    // instance.$mount() 只会生成一个$el对象，并没有插入到dom节点中
    // console.log(instance.$mount())
    instance.vm = instance.$mount()
    
    // console.log(instance.vm)
    document.body.appendChild(instance.vm.$el)

    // 把visible设置为true，才能触发transition，才能执行afterEnter
    // 才能设置组件的高度
    instance.vm.visible = true

    // 每个notification的间距
    let verticalOffset = 0
    instances.forEach(item => {
        // console.log("**************")
        // console.log(item.$el)
        verticalOffset += item.$el.offsetHeight + 16
    }) 

    verticalOffset += 16
    instance.verticalOffset = verticalOffset
    // 添加到数组中
    instances.push(instance)

    // 给instance.vm 添加关闭事件
    instance.vm.$on('closed',() => {
        // console.log(instance.vm)
        // 从数组中干掉instance
        removeInstance(instance)
        // 把 dom 节点从body中移除
        document.body.removeChild(instance.vm.$el)
        // 把instance.vm销毁掉
        instance.vm.$destroy()
    })

    // 手动关闭事件
    instance.vm.$on('close',() => {
        instance.vm.visible = false
    })

    return instance.vm
}

export default notify